import {
  AddDrawingPriceData,
  CreatedSame,
  DeleteDrawingPrice,
  GetDrawingSameList,
  GetMyDrawingHistoryList,
  GetRandomValueInfo
} from "@/api/drawing"
import { PriceResizeListProps } from "@/api/drawing/types"
import debounce from "@/utils/debounce"
import { ElMessage, ElMessageBox } from "element-plus"
import Pubsub from "pubsub-js"
import { computed, ref } from "vue"
import { DrawingDataProps, DrawingFormProps, getImages, priceResizeList } from "./components/type"

export type CoverType = "plaza" | "data"

export interface ImageListProps {
  path: string
  name: string
}

export interface PaginationProps {
  page: number
  pageSize: number
  count: number
}

const PAGE_SIZE = 20
export default function useCover() {
  const pagination = ref<PaginationProps>({
    page: 1,
    pageSize: 0,
    count: 0
  })
  const resizeId = ref<number>(1)
  const imgCurrentIndex = ref<number>(-1)
  const submitLoading = ref<boolean>(false)
  const sameLoading = ref<boolean>(false)
  const loading = ref<boolean>(false)
  const immediate = ref<boolean>(false)
  const plazaLoading = ref<boolean>(false)
  const dataLoading = ref<boolean>(false)
  const vocabularyList = ref<string[]>([""])
  const imageList = ref<ImageListProps[]>([])
  const cmdForm = ref<DrawingFormProps>({
    command: "",
    cmd_proportion: priceResizeList[0].scale, // 默认选择初始化比例
    cmd_auxiliary: "",
    cmd_style: "",
    model: "base"
  })
  const coverList = ref<DrawingDataProps[]>([])
  const plazaList = ref<{ id: string; src: string }[]>([])

  // 页数
  const pageCount = computed(() => {
    return Math.ceil(pagination.value.count / PAGE_SIZE)
  })

  const initCoverDataList = async (type: CoverType) => {
    let list = []
    try {
      loading.value = true
      if (type === "plaza") {
        const { data } = await GetDrawingSameList({ page: pagination.value.page })
        pagination.value.count = data.count
        // @ts-ignore
        list = data.list.map((item) => {
          return {
            id: String(item.id),
            src: String(item.cos_url)
          }
        })
        // 将上一次的数据做连接
        // for (const key in list) {
        //   plazaList.value.push(list[key])
        // }
        // plazaList.value = plazaList.value.push.apply(list)
      } else {
        const { data } = await GetMyDrawingHistoryList({ page: pagination.value.page })
        pagination.value.count = data.count
        list = data.list
        // 将上一次的数据做连接
        // for (const key in list ) {
        //   coverList.value.push(list[key])
        // }
        // coverList.value = coverList.value.push.apply(data.list)
      }
    } catch (error) {
      console.error(error)
    } finally {
      loading.value = false
    }

    return list
  }

  const handleImageDeleteId = async (id: number) => {
    const res = await ElMessageBox.confirm("相关绘画图形将永久删除，请谨慎操作！是否继续删除？", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    if (res === "confirm") {
      await DeleteDrawingPrice({ id })
    }
  }

  const getImageList = () => {
    getImages()
      .then((imgs: any) => {
        imageList.value = imgs
      })
      .catch((error) => {
        console.error("获取图片列表时发生错误：", error)
      })
  }

  const handleChangeResize = debounce((item: PriceResizeListProps) => {
    resizeId.value = item.id
    cmdForm.value.cmd_proportion = item.scale
  }, 300)

  const handleSelectChange = debounce((val: string, index: number) => {
    vocabularyList.value[index] = val
    cmdForm.value.cmd_auxiliary = vocabularyList.value.filter((item) => item).join(",")
  }, 200)

  const handleChangeImg = debounce((item: any, index: number) => {
    imgCurrentIndex.value = index
    cmdForm.value.cmd_style = item.name
  }, 200)

  const handleGenerateRandomValue = debounce(async () => {
    try {
      const { data } = await GetRandomValueInfo()
      cmdForm.value.command = data?.info ?? ""
    } catch (error) {
      console.error(error)
    }
  }, 200)

  const handleSubmit = debounce(async () => {
    try {
      submitLoading.value = true
      // 先触发socket, 再调用submit接口
      // await Speech.instance.getDoPic(cmdForm.value.command)

      await AddDrawingPriceData(cmdForm.value)
      ElMessage({
        type: "success",
        message: "提交成功"
      })
      Pubsub.publish("UPDATE_DATA_INIT")
      // 清空表单
      cmdForm.value = {
        command: "",
        cmd_proportion: priceResizeList[0].scale, // 默认选择初始化比例
        cmd_auxiliary: "",
        cmd_style: "",
        model: "base"
      }
      resizeId.value = priceResizeList[0].id
      imgCurrentIndex.value = -1
      vocabularyList.value = [""]
    } catch (error: any) {
      console.error("error", error)
      ElMessage({
        message: error.message || "提交失败",
        type: "error"
      })
    } finally {
      submitLoading.value = false
    }
  }, 300)

  // 下一页
  const nextPage = debounce(async () => {
    console.log("scroll")
    if (pagination.value.page >= pageCount.value) {
      return
    }
    pagination.value.page += 1
    immediate.value = true
    Pubsub.publish("UPDATE_COVER_LIST")
  }, 200)

  const handleCreateTheSame = debounce(async (id: number) => {
    try {
      sameLoading.value = true
      loading.value = true
      const result = await CreatedSame({ id })
      if (result.code === 200) {
        ElMessage({
          type: "success",
          message: "创建成功，等待绘画图片生成..."
        })
        Pubsub.publish("UPDATE_DATA_INIT")
      } else {
        ElMessage({
          type: "error",
          message: result.error
        })
      }
    } catch (error) {
      console.error(error)
    } finally {
      sameLoading.value = false
      loading.value = false
    }
  }, 300)

  return {
    sameLoading,
    loading,
    pagination,
    pageCount,
    resizeId,
    imgCurrentIndex,
    submitLoading,
    vocabularyList,
    imageList,
    cmdForm,
    coverList,
    plazaList,
    immediate,
    plazaLoading,
    dataLoading,
    initCoverDataList,
    handleImageDeleteId,
    nextPage,
    getImageList,
    handleChangeResize,
    handleSelectChange,
    handleChangeImg,
    handleGenerateRandomValue,
    handleSubmit,
    handleCreateTheSame
  }
}
